const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { getPassword } = require('../utils/crypto')
const { exec } = require('../db')
// 登陆注册写成一个接口
router.post('/api/signIn', async (ctx, next) => {
	// 登陆 / 注册
	const { username, password, avatar, nickname = '' } = ctx.request.body
	const userData = await exec(`select * from users where username=?`, [
		username
	])
	if (userData.length !== 0) {
		// 登陆
		const loginData = await exec(
			`select * from users where username=? and password=?`,
			[username, getPassword(password)]
		)

		// token （给前端用户这个token,让用户方便登陆）
		const token = jwt.sign(
			// 第一个参数 个人信息
			{
				id: loginData[0].id,
				username: loginData[0].username
			},
			'1904-secret', // 某个密钥
			{ expiresIn: '24h' } // 实效性 （过了这个时间，token失效）
		)
		ctx.body = {
			code: 0,
			msg: 'success',
			data: token
		}
	} else {
		// 注册
		const registerData = await exec(
			`insert into users (username, password, avatar, nickname) values (?,?,?,?)`,
			[username, getPassword(password), avatar, nickname]
		)
		ctx.body = {
			code: 0,
			msg: '注册成功',
			data: registerData
		}
	}
})

// 用户查询接口 分页
router.get('/api/users', async (ctx, next) => {
	const { id } = ctx.state.userInfo
	console.log('id:', id)
	const { page = 1, size = 5 } = ctx.query
	const pageData = await exec(
		`select * from users where id=? limit ? offset ? `,
		[id, size * 1, (page - 1) * size]
	)
	ctx.body = {
		code: 0,
		msg: 'success',
		data: pageData
	}
})

module.exports = router
